/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.andersen.web.controller;

import com.andersen.database.entity.ComponentEntity;
import com.andersen.database.entity.EmployeeEntity;
import com.andersen.database.entity.OfficeEntity;
import com.andersen.database.entity.StateEntity;
import com.andersen.web.beans.ComponentCommandForm;
import com.andersen.web.beans.NewComponentCommandForm;
import static com.andersen.web.controller.AbstractController.ERROR_DATA_PROCESSING_FAILED;
import com.andersen.web.exception.ServiceException;
import com.andersen.web.validating.ComponentPropertiesValidator;
import com.andersen.web.validating.NewComponentValidator;
import java.io.IOException;
import java.sql.Date;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;

/**
 *
 * @author Corvus 11
 */
@Controller
public class ComponentsController extends AbstractController{
    
    private static final long ROOT_CATHEGORY = 0l;
    
    @Autowired
    ComponentPropertiesValidator propertiesValidator;
    
    @Autowired
    NewComponentValidator newCompValidator;
    
    
    @RequestMapping(value="/components", method= RequestMethod.GET)
    public String openComponentPage() {
        return VIEW_COMPONENTS;
    }
    
    //@ModelAttribute(value = "tree")
    //public String populateTypeTree() {
//        return componentTypeService.getComponentTypeTree().toHTML();
//    }
    
    @RequestMapping(value = "/a_get_type_tree", method= RequestMethod.GET)
    public @ResponseBody JSONObject getTypeTree() {
        return componentTypeService.getComponentTypeTree().toViewJSON();
    }
    
    @RequestMapping(value = "/a_get_component_table_data", method= RequestMethod.GET)
    public @ResponseBody JSONObject getComponentTableData(HttpServletRequest req) throws IOException {
        
        int offset = requestUtils.getIntegerParam(req,PARAM_NAME_DISPLAY_START);
        int count = requestUtils.getIntegerParam(req,PARAM_NAME_DISPLAY_COUNT);
        
        int sortNum = requestUtils.getIntegerParam(req,PARAM_NAME_SORT_BY);
        int sortDir = (PARAM_VAL_SORT_ASC.equals(req.getParameter(PARAM_NAME_SORT_ORDER))) ? 
                componentsService.SORT_DIRECTION_ASC : componentsService.SORT_DIRECTION_DESC;
        long mainCat = requestUtils.getLongParam(req,"cathegory");

        List<Long> cats = (mainCat == ROOT_CATHEGORY)? null : 
                componentTypeService.getComponentTypeTree().getBranchIndexes(mainCat);
        
        ArrayList<StateEntity> states = stateService.queryForComponentTable(offset, 
                                                                            count,
                                                                            sortNum, 
                                                                            sortDir, 
                                                                            cats);
        
        JSONArray arr = new JSONArray();
        for(int i=0;i<states.size();i++) {
            JSONObject jobj = dataTableJsonUtils.StateToDataTableRow(states.get(i));
            arr.add(jobj);
        }
        
        JSONObject result = new JSONObject();
        result.accumulate(RESULT_ATTRIBUTE_DATA, arr);
        result.accumulate(RESULT_ATTRIBUTE_ECHO, req.getParameter(PARAM_NAME_ECHO)); 
        
        result.accumulate(RESULT_ATTRIBUTE_TOTAL_RECORDS, stateService.countCurrentStates(null));
        result.accumulate(RESULT_ATTRIBUTE_DISPLAY_RECORDS, stateService.countCurrentStates(cats));
        
        return result;
        
    }
    
    @RequestMapping(value = "/a_component_properties", method = RequestMethod.GET)
    public String getComponentProperties(@RequestParam(value="componentId", required = true) String componentId,
                                                     ModelMap model) throws IOException {
        LOG.info("[/a_component_properties] mapped");
        long id = Long.parseLong(componentId);
        
        ComponentEntity comp;
        comp = componentsService.getById(id);
        comp.setComponentType(componentTypeService.getById(comp.getTypeId()));
         
        ComponentCommandForm cf = ComponentCommandForm.fromEntity(comp);
        
        model.addAttribute("componentCommandForm", cf);
        
        LOG.info(cf.toString());
        
        String viewName = (comp.getDeleted()) ? VIEW_DIALOG_COMPONENT_PROPERTIES_READONLY :
                VIEW_DIALOG_COMPONENT_PROPERTIES;
        
        return viewName;
    }

    @RequestMapping(value = "/a_get_jscomponents", method = RequestMethod.GET)
    public @ResponseBody JSONObject getJSComponents() throws IOException {
        
        JSONObject json = componentTypeService.getComponentTypeTree().toOptionTreeJSON();
        
        return json;
    }
    
    @RequestMapping(value = "/a_edit_component_data", method = RequestMethod.POST)
    public String submitComponentData(@ModelAttribute("componentCommandForm") ComponentCommandForm command,
            BindingResult result, SessionStatus status, HttpServletResponse response) throws IOException {
        
        propertiesValidator.validate(command, result);
        
        if (result.hasErrors()) {
            command.setValidationError(true);
        } else {
            ComponentEntity comp = ComponentEntity.fromCommandForm(command);
        
            LOG.info(comp.toString());
        
            if (componentsService.updateComponent(comp)) {
                command.setValidationError(false);
            } else {
                command.setValidationError(true);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            }
        }
       
        return VIEW_DIALOG_COMPONENT_PROPERTIES;
    }
    
    @RequestMapping(value="/a_new_component", method=RequestMethod.GET)
    public String getNewComponentDialog(ModelMap model) {
        
        NewComponentCommandForm form = new NewComponentCommandForm();
        
        model.addAttribute("newComponentCommandForm", form);
        
        List<OfficeEntity> officeNameList = officeService.getOfficeList();
        
        model.addAttribute("officeNameList",officeNameList);
        
        return VIEW_DIALOG_NEW_COMPONENT_DATA;
    }
    
    @RequestMapping(value = "/a_get_working_employees_from", method = RequestMethod.GET)
    public @ResponseBody JSONArray getWorkingEmployeesFrom(@RequestParam(value = "officeId", required = true)
                                                            String employeeId) throws IOException {
        long id = Long.parseLong(employeeId);
        ArrayList<EmployeeEntity> empl = 
                employeeService.getWorkingEmployees(id);
        JSONArray arr = new JSONArray();
        for(int i=0;i<empl.size();i++) {
            JSONObject jobj = new JSONObject();
            jobj.accumulate("id", empl.get(i).getId());
            jobj.accumulate("surnameNamePatronymic", empl.get(i).getSurnameNamePatronymic());
            arr.add(jobj);
        }
        LOG.info(arr.toString());
        return arr;
    }
    
    @RequestMapping(value="/a_get_computers_for", method = RequestMethod.GET)
    public @ResponseBody JSONArray getComputersFor(@RequestParam(value="emplId", required = true)
                                                    String emplId) throws IOException {
        long id = Long.parseLong(emplId);
        List<ComponentEntity> computers = componentsService.getMajorComponentsForEmployee(id);
        
        JSONArray array = new JSONArray();
        for(ComponentEntity c : computers) {
            JSONObject jobj = new JSONObject();
            jobj.accumulate("id", c.getId());
            jobj.accumulate("description", c.getDescription());
            array.add(jobj);
        }
        
        return array;
    }
    
    @RequestMapping(value = "/a_submit_component_data", method = RequestMethod.POST)
    public String newComponentNext(@ModelAttribute("newComponentCommandForm") NewComponentCommandForm command,
            BindingResult result, SessionStatus status, HttpServletResponse response, ModelMap model) throws IOException {
        
        
        newCompValidator.validate(command, result);
        
        if (result.hasErrors()) {
            command.setValidationError(true);
            command.setOfficeId(ID_INVALID);
            List<OfficeEntity> officeNameList = officeService.getOfficeList();
        
            model.addAttribute("officeNameList",officeNameList);
            return VIEW_DIALOG_NEW_COMPONENT_DATA;
        } else {
            command.setStep(2);
            LOG.info(command);
            model.addAttribute("newComponentCommandForm", command);
            
            List<EmployeeEntity> employees = employeeService.getWorkingEmployees(command.getOfficeId());
            
            model.addAttribute("employeeList",employees);
            
            return VIEW_DIALOG_NEW_COMPONENT_RELATION;
        }
    }
    
    @RequestMapping(value = "/a_get_components_by_type", method = RequestMethod.GET)
    public @ResponseBody JSONObject getComponents(@RequestParam(value = "typeId", required = true) String typeId) {
        
        LOG.info("[/a_get_components_by_type] mapped");
        
        JSONObject result = new JSONObject();
        JSONArray arr = new JSONArray();
        
        long id = Long.parseLong(typeId);
        
        List<Long> cats = componentTypeService.getComponentTypeTree().getBranchIndexes(id);
        
        List <ComponentEntity> components = componentsService.getComponentsByTypeIds(cats);
        
        for(ComponentEntity c : components) {
            JSONObject obj = new JSONObject();
            obj.accumulate("id", c.getId());
            obj.accumulate("name", c.getDescription());
            arr.add(obj);
        }
        
        LOG.info(arr.toString());
        
        result.accumulate("data", arr);
        
        return result;
    }
    
    @RequestMapping(value = "/a_submit_component", method = RequestMethod.POST)
    public String submitNewComponent(@ModelAttribute("newComponentCommandForm") NewComponentCommandForm command,
            BindingResult result, SessionStatus status, HttpServletResponse response, ModelMap model) throws IOException {
        
            ComponentEntity component = ComponentEntity.fromCommandForm(command);

            command.setValidationError(false);
            
            long compId = (command.getComputerId() > 0)? command.getComputerId() : ID_NOT_DEFINED;
            long emplId = (compId == ID_NOT_DEFINED && command.getEmployeeId() > 0)? 
                    command.getEmployeeId() : ID_NOT_DEFINED;
            long officeId = command.getOfficeId();
            if (compId > ID_NOT_DEFINED) {
                StateEntity computerState = stateService.getLastStateOfComponent(compId);
                
                if (officeId != computerState.getOfficeId())
                    officeId = computerState.getOfficeId();
                
                if (computerState.getComputerId() > ID_NOT_DEFINED) {
                    result.rejectValue("computerId", "incorrect.computerId");
                    command.setValidationError(true);
                }
            }
            if (emplId > ID_NOT_DEFINED) {
                EmployeeEntity employee = employeeService.getEmployee(emplId);
                if (officeId != employee.getOfficeId())
                    officeId = employee.getOfficeId();
            }
            Date fromDate = new Date(Calendar.getInstance().getTime().getTime());
            
            char stat = (PARAM_VAL_STATUS_OK.equals(command.getStatus()))? StateEntity.STATUS_OK :
                    command.getStatus().charAt(0);

            StateEntity firstState = new StateEntity();
            firstState.setComputerId(compId);
            firstState.setEmployeeId(emplId);
            firstState.setOfficeId(officeId);
            firstState.setFromDate(fromDate);
            firstState.setStatus(stat);

            long[] keys = componentsService.addComponent(component, firstState);

            if (keys[0] == ID_INVALID || keys[1] == ID_INVALID) {
                command.setValidationError(true);
                command.setOfficeId(ID_INVALID);
                response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
            }
        //}
            if (command.isValidationError()) {
                command.setStep(2);
                model.addAttribute("newComponentCommandForm", command);
                List<EmployeeEntity> employees = employeeService.getWorkingEmployees(command.getOfficeId());
                model.addAttribute("employeeList",employees);
            }
            
        
        return VIEW_DIALOG_NEW_COMPONENT_RELATION;

    }
    
    
    @RequestMapping(value = "/a_set_component_status", method = RequestMethod.POST)
    public @ResponseBody JSONObject setComponentStatus(@RequestParam(value = "compId", required = true) String componentId,
                                                 @RequestParam(value = "newStatus", required = true) String newStatus,
                                                 @RequestParam(value = "date", required = true) String dateStr,
                                                 HttpServletResponse response) throws IOException {
        long id = Long.parseLong(componentId);
        char st = (PARAM_VAL_STATUS_OK.equals(newStatus)) ? 
                StateEntity.STATUS_OK : newStatus.charAt(0);
        Date date;
       // Date today = new Date(Calendar.getInstance().getTime().getTime());
        
        JSONObject json = new JSONObject();
        try {
            date = new Date(localDateFormat.parse(dateStr).getTime());
        } catch (ParseException ex) {
            throw new IOException(ex);
        }
        
        String error = changeComponentStatus(date, id, st);
        json.accumulate(RESULT_ATTRIBUTE_ERROR_VAL, error);
        
        if (ERROR_DATA_PROCESSING_FAILED.equals(error)) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        }
        
        return json;
    }
    
    private String changeComponentStatus(Date changeDate, long componentId, char status) {
        String errorVal = ERROR_VAL_OK;
        
        Date today = new Date(Calendar.getInstance().getTime().getTime());
        
        if (changeDate.after(today)) {
            errorVal = ERROR_STATE_DATE_IN_FUTURE;
        } else {
            long retId;
            try {
                retId = stateService.changeComponentStatus(componentId, status, changeDate);
                if (retId <= ID_NOT_DEFINED) {
                    errorVal = ERROR_DATA_PROCESSING_FAILED;
                }
            } catch (ServiceException exc) {
                errorVal = ERROR_STATE_DATE_BUSY;
            }
        }
        return errorVal;
    }
    
    @RequestMapping(value="/a_dialog_delete_component", method = RequestMethod.GET)
    public String dialogDeleteComponent(@RequestParam(value = "id", required = true) String compId,
                                              ModelMap model) {
        long id = Long.parseLong(compId);
        StateEntity lastState = stateService.getLastStateOfComponent(id);
        LOG.info("ComponentsComtroller.dialogDeleteComponent() - last state: " + lastState);
        ComponentEntity computer = null;
        EmployeeEntity employee = null;
        
        if (lastState.getComputerId() > ID_NOT_DEFINED) {
             computer = componentsService.getById(lastState.getComputerId());
             computer.setComponentType(componentTypeService.getById(computer.getTypeId()));
             LOG.info("ComponentsComtroller.dialogDeleteComponent() - computer: " + computer);
        }
        model.addAttribute(RESULT_ATTRIBUTE_DISCONNECTED_COMPUTER, computer);
        if (lastState.getEmployeeId() > ID_NOT_DEFINED) {
            employee = employeeService.getEmployee(lastState.getEmployeeId());
            LOG.info("ComponentsComtroller.dialogDeleteComponent() - employee: " + employee);
        }
        model.addAttribute(RESULT_ATTRIBUTE_DISCONNECTED_EMPLOYEE, employee);
        List<ComponentEntity> subComponents = componentsService.getConnectedComponents(lastState.getComponentId());
        if (subComponents.size() > 0) {
            for(ComponentEntity c : subComponents) {
                c.setComponentType(componentTypeService.getById(c.getTypeId()));
                LOG.info("ComponentsComtroller.dialogDeleteComponent() - component: " + c);
            }
        } else { 
            subComponents = null;
        }
        model.addAttribute(RESULT_ATTRIBUTE_DISCONNECTED_COMPONENTS, subComponents);
        
        model.addAttribute(RESULT_ATTRIBUTE_DELETED_COMPONENT_ID, compId);
        return VIEW_DIALOG_DELETE_COMPONENT;
    }
            
    @RequestMapping(value="/a_dialog_delete_component", method = RequestMethod.POST)
    public @ResponseBody JSONObject submitDeleteComponent(@RequestParam(value = "id", required = true) String compId,
                                                          @RequestParam(value = "date", required = true) String dateStr,
                                                          HttpServletResponse response) throws IOException {
        JSONObject json = new JSONObject();
        long id = Long.parseLong(compId);
        ComponentEntity component = componentsService.getById(id);
        Date date;
        
        try {
            date = new Date(localDateFormat.parse(dateStr).getTime());
        } catch (ParseException ex) {
            throw new IOException(ex);
        }
        
        String error = processComponentDiscard(date,id);
        
        json.accumulate(RESULT_ATTRIBUTE_ERROR_VAL, error);
        
        if (ERROR_DATA_PROCESSING_FAILED.equals(error)) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        }
        
        component.setDeleted(true);
        if (!componentsService.updateComponent(component)) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        }
        
        return json;
    }
    
    private String processComponentDiscard(Date discardDate, long componentId) {
        List<ComponentEntity> subComponents = componentsService.getConnectedComponents(componentId);
        StateEntity lastState = stateService.getLastStateOfComponent(componentId);
        long officeId = lastState.getOfficeId();
        long computerId = lastState.getComputerId();
        long employeeId = lastState.getEmployeeId();
        Date today = new Date(Calendar.getInstance().getTime().getTime());
        
        String errorVal = ERROR_VAL_OK;
        
        if (discardDate.after(today)) {
            errorVal = ERROR_STATE_DATE_IN_FUTURE;
        } else  {
            try {
                if (computerId > ID_NOT_DEFINED || employeeId > ID_NOT_DEFINED) {
                    long retId;
                        if (computerId > ID_NOT_DEFINED) {
                            retId = stateService.moveComponentToComputer(componentId,ID_NOT_DEFINED,discardDate,officeId);
                        } else {
                            retId = stateService.moveComponentToEmployee(componentId,ID_NOT_DEFINED,discardDate,officeId);
                        }
                        if (retId <= ID_NOT_DEFINED) {
                            errorVal = ERROR_DATA_PROCESSING_FAILED;
                        }
                }
                if (subComponents.size() > 0) {
                    long subId = ID_INVALID;
                    for (ComponentEntity c : subComponents) {
                        subId = stateService.moveComponentToComputer(c.getId(), ID_NOT_DEFINED, discardDate, officeId);
                        if (subId <= ID_NOT_DEFINED) break;
                    }
                    if (subId <= ID_NOT_DEFINED) {
                        errorVal = ERROR_DATA_PROCESSING_FAILED;
                    }
                }
            } catch (ServiceException exc) {
                    errorVal = ERROR_STATE_DATE_BUSY;
            }
        }
        
        return errorVal;   
    }
    
    @RequestMapping(value = "/a_dialog_move_to_employee", method = RequestMethod.GET)
    public String loadDialogMoveToEmployee(@RequestParam(value = "getNew", required = true) String getNew,
                                           ModelMap model) {
        
        boolean selectNewEmployee = Boolean.parseBoolean(getNew);
        
        model.addAttribute("getNew", selectNewEmployee);
        
        if (selectNewEmployee) {
            List<OfficeEntity> offices = officeService.getOfficeList();
            model.addAttribute("officeNameList", offices);
        }
        
        return VIEW_DIALOG_MOVE_COMPONENT_TO_EMPLOYEE;
    }
    
    @RequestMapping(value = "/a_dialog_move_to_employee", method = RequestMethod.POST)
    public @ResponseBody JSONObject submitComponentEmployeeMove(@RequestParam(value = "compId", required = true) String compId,
                                                 @RequestParam(value = "emplId", required = true) String emplId,
                                                 @RequestParam(value = "offcId", required = true) String offcId,
                                                 @RequestParam(value = "date", required = true) String dateStr,
                                                 HttpServletResponse response) throws IOException {
        long componentId = Long.parseLong(compId);
        long employeeId = Long.parseLong(emplId);
        long officeId = Long.parseLong(offcId);
        if (officeId == ID_INVALID)
            officeId = stateService.getLastStateOfComponent(componentId).getOfficeId();
        Date date;
        //Date today = new Date(Calendar.getInstance().getTime().getTime());
        
        JSONObject json = new JSONObject();
        //String errorVal = "OK";
        try {
            date = new Date(localDateFormat.parse(dateStr).getTime());
        } catch (ParseException ex) {
            throw new IOException(ex);
        }
        
        String error = changeComponentEmployee(componentId, employeeId, officeId, date);
        json.accumulate(RESULT_ATTRIBUTE_ERROR_VAL, error);
        
        if (ERROR_DATA_PROCESSING_FAILED.equals(error)) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        }
        
        return json;
    }
    
    private String changeComponentEmployee(long componentId, long employeeId, long officeId, Date moveDate) {
        Date today = new Date(Calendar.getInstance().getTime().getTime());
        String errorVal = ERROR_VAL_OK;
        
        if (moveDate.after(today)) {
            errorVal = ERROR_STATE_DATE_IN_FUTURE;
        } else  {
            long retId;
            try {
                retId = stateService.moveComponentToEmployee(componentId,employeeId,moveDate,officeId);
                if (retId <= ID_NOT_DEFINED) {
                    errorVal = ERROR_DATA_PROCESSING_FAILED;
                }
            } catch (ServiceException exc) {
                errorVal = ERROR_STATE_DATE_BUSY;
            }
        }
        
        return errorVal;
    }
    
    @RequestMapping(value = "/a_dialog_move_to_office", method = RequestMethod.GET)
    public String loadDialogMoveToOffice(@RequestParam(value = "componentId", required = true) String componentIdStr,
                                          ModelMap model) {
        
        long componentId = Long.parseLong(componentIdStr);
        
        List<ComponentEntity> subComponents = componentsService.getConnectedComponents(componentId);
        if (subComponents.size() > 0) {
            for(ComponentEntity c : subComponents) {
                c.setComponentType(componentTypeService.getById(c.getTypeId()));
                LOG.info("ComponentsComtroller.loadDialogMoveToOffice() - component: " + c);
            }
        } else { 
            subComponents = null;
        }
        model.addAttribute(RESULT_ATTRIBUTE_MOVED_COMPONENTS, subComponents);
        
        
        List<OfficeEntity> offices = officeService.getOfficeList();
        model.addAttribute("officeNameList", offices);
        
        model.addAttribute("movedId",componentId);
        
        return VIEW_DIALOG_MOVE_COMPONENT_TO_OFFICE;
    }
    
    @RequestMapping(value = "/a_dialog_move_to_office", method = RequestMethod.POST)
    public @ResponseBody JSONObject submitComponentOfficeMove(@RequestParam(value = "compId", required = true) String compId,
                                                 @RequestParam(value = "offcId", required = true) String offcId,
                                                 @RequestParam(value = "date", required = true) String dateStr,
                                                 HttpServletResponse response) throws IOException {
        long componentId = Long.parseLong(compId);
        long officeId = Long.parseLong(offcId);
        Date date;
        
        JSONObject json = new JSONObject();
        
        try {
            date = new Date(localDateFormat.parse(dateStr).getTime());
        } catch (ParseException ex) {
            throw new IOException(ex);
        }
        
        String error = changeComponentOffice(componentId, officeId, date);
        
        json.accumulate(RESULT_ATTRIBUTE_ERROR_VAL, error);
        
        if (ERROR_DATA_PROCESSING_FAILED.equals(error)) {
            response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
        }
        
        return json;
    }
    
    private String changeComponentOffice(long componentId, long officeId, Date moveDate) {
        Date today = new Date(Calendar.getInstance().getTime().getTime());
        String errorVal = ERROR_VAL_OK;
        
        if (moveDate.after(today)) {
            errorVal = ERROR_STATE_DATE_IN_FUTURE;
        } else  {
            long retId;
            try {
                retId = stateService.moveComponentToOffice(componentId,officeId,moveDate);
                if (retId <= ID_NOT_DEFINED) {
                    //response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                    errorVal = ERROR_DATA_PROCESSING_FAILED;
                }
                List<ComponentEntity> subComponents = componentsService.getConnectedComponents(componentId);
                if (subComponents.size() > 0) {
                    long subId = ID_INVALID;
                    for (ComponentEntity c : subComponents) {
                        subId = stateService.moveComponentToOffice(c.getId(), officeId, moveDate);
                        if (subId <= ID_NOT_DEFINED) break;
                    }
                    if (subId <= ID_NOT_DEFINED) {
                        //response.setStatus(response.SC_INTERNAL_SERVER_ERROR);
                        errorVal = ERROR_DATA_PROCESSING_FAILED;
                    }
                }
            } catch (ServiceException exc) {
                errorVal = ERROR_STATE_DATE_BUSY;
            }
        }
        return errorVal;
    }
}
